import axios from 'axios'
import { globalConfig } from './global'
import { getCookieItem, delCookieItem } from './cookies'
const CancelToken = axios.CancelToken
const source = CancelToken.source()
/**
 * 请求聚合后端使用
 */
const http = axios.create({
  baseURL: '/api/work-wechat',
  timeout: 60 * 1000
})

http.interceptors.request.use((config: any) => {
  // 每次请求添加请求记录
  config.cancelToken = source.token
  const accessToken: string | null = getCookieItem('access_token')
  if (accessToken != null) {
    config.headers.Authorization = `Bearer ${accessToken}`
  }
  return config
})

http.interceptors.response.use(
  (res: any) => {
    // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
    if (res.headers['x-pagination-count']) {
      res.pageInfo = {
        count: parseInt(res.headers['x-pagination-count']),
        number: parseInt(res.headers['x-pagination-number']),
        pages: parseInt(res.headers['x-pagination-pages']),
        size: parseInt(res.headers['x-pagination-size'])
      }
    }
    return res
  },
  (error) => {
    const status = error.response.status
    if (status === 401) {
      source.cancel()
      // console.log('401', error.response.data)
      delCookieItem('access_token')
      const agentid: any = localStorage.getItem('agentid')
      const mode = import.meta.env.MODE
      const clientId: string = globalConfig[mode][agentid].clientId
      const callbackUrl = `${location.origin}/callback`
      const authUrl: string = import.meta.env.VITE_APP_AUTH_URL
      // 跳转中台认证登录页面
      window.location.href = `${authUrl}/oauth/authorize?response_type=code&client_id=${clientId}&redirect_uri=${callbackUrl}&state=1`
    } else {
      return Promise.reject(error.response)
    }
  }
)

export default {
  http,
  async post (url: string, data?: any, headers?: any) {
    return await http({
      method: 'post',
      url,
      data,
      headers
    })
  },
  async get (url: string, params?: any, headers?: any) {
    return await http({
      method: 'get',
      url,
      params,
      headers
    })
  },
  async put (url: string, data?: any, headers?: any) {
    return await http({
      method: 'put',
      url,
      data,
      headers
    })
  },
  async delete (url: string, data?: any) {
    return await http({
      method: 'delete',
      url,
      data
    })
  },
  async patch (url: string, data?: any) {
    return await http({
      method: 'patch',
      url,
      data
    })
  }
}
